package cn.virens.common.boot.filter.autoconfig;

import cn.virens.common.boot.filter.FilterRegistrationBeanAware;
import cn.virens.common.boot.filter.logging.SimpleHandlerLoggingFilter;
import cn.virens.common.boot.filter.logging.SimpleHandlerLoggingProperties;
import cn.virens.common.util.exception.APIException;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

@AutoConfiguration
@EnableConfigurationProperties(SimpleHandlerLoggingProperties.class)
@ConditionalOnProperty(prefix = "virens.filter.logging", value = "enabled")
public class SimpleHandlerLoggingAutoConfig {

    @Bean(value = "simpleHandlerLoggingFilter")
    @ConditionalOnMissingBean(name = "simpleHandlerLoggingFilter")
    public FilterRegistrationBean<SimpleHandlerLoggingFilter> simpleHandlerLoggingFilter(SimpleHandlerLoggingProperties properties) throws APIException {
        SimpleHandlerLoggingFilter authenticationFilter = new SimpleHandlerLoggingFilter();
        properties.pushBlackPatterns(authenticationFilter::addBlackPatterns);
        properties.pushWhitePatterns(authenticationFilter::addWhitePatterns);

        var registrationBean = new FilterRegistrationBeanAware<SimpleHandlerLoggingFilter>();
        registrationBean.setOrder(SimpleFilterOrdered.FILTER_LOGGING);
        registrationBean.setFilter(authenticationFilter);
        registrationBean.addUrlPatterns("/*");

        return registrationBean;
    }
}
